//
//  WMSearchViewController.swift
//  iiatn
//
//  Created by mine on 18/5/11.
//  Copyright © 2018年 mnine. All rights reserved.
//

import UIKit

class WMSearchViewController: UIViewController, UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource {

    /// 搜索结果列表
    var items = [WPro]()
    weak var tableView: UITableView?
    var words = [String]()
    
    
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        searchBar.becomeFirstResponder()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        searchBar.resignFirstResponder()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupNav()
        weak var weakSelf = self
        WNetwork.shareNetworkTool.loadHotWords{ (hot_words) in
            weakSelf!.words = hot_words
            //weakSelf!.setRecordView()
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    // 设置导航栏
    func setupNav() {
        navigationItem.titleView = searchBar
        searchBar.delegate = self
        navigationItem.leftBarButtonItem = UIBarButtonItem(customView: UIView())
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: .plain, target: self, action: #selector(navigationBackClick))
    }
    
    // 设置tableview
    func setupTableView() {
        let tableView = UITableView(frame: view.bounds)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.rowHeight = 150
        // 分割线
        tableView.separatorStyle = .singleLine
        // top left bottom right
        tableView.contentInset = UIEdgeInsetsMake(kTitlesViewY, 0, 0, 0)
        tableView.scrollIndicatorInsets = tableView.contentInset
        /// 切入视图cell，并注册
        let nib = UINib(nibName: String(describing: WProViewCell.self), bundle: nil)
        tableView.register(nib, forCellReuseIdentifier: proCellID)
        view.addSubview(tableView)
        self.tableView = tableView
    }
    
    private lazy var searchBar: UISearchBar = {
        let searchBar = UISearchBar()
        searchBar.placeholder = "搜索项目关键词"
        return searchBar
    }()
    
    /// 返回按钮、取消按钮点击
    func navigationBackClick() {
        let back = navigationController?.popViewController(animated: true)
        print("\(back)")
    }
    
    func dosearch(button: UIButton){
        print("dosearch")
        let key = button.title(for: .normal)
        toSearch(key: key!)
    }
    
    // 搜索结束编辑后
    func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool {
        setupTableView()
        return true
    }
    
    /// 搜索按钮点击
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        searchBar.resignFirstResponder()
        navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "checkUserType_backward_9x15_"), style: .plain, target: self, action: #selector(navigationBackClick))
        /// 根据搜索条件进行搜索
        let keyword = searchBar.text
        weak var weakSelf = self
        WNetwork.shareNetworkTool.loadSearch(key: keyword!) { (results) in
            weakSelf!.items = results
            weakSelf!.tableView!.reloadData()
        }
    }
    // 书签按钮触发事件
    func searchBarBookmarkButtonClicked(_ searchBar: UISearchBar) {
        print("搜索历史")
    }
    
    // MARK: - Table view data source
    func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
        // return items.count
    }
    
    // 一共多少行
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return items.count
    }
    
    // 行数据定义
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: proCellID) as! WProViewCell
        cell.selectionStyle = .gray
        cell.proItem = items[indexPath.row]
        
        return cell
    }
    
    // MARK: - UITableViewDelegate
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if whaslogin!{
            let detailVC = WProDetailViewController()
            detailVC.proItem = items[indexPath.row]
            detailVC.title = " "
            navigationController?.pushViewController(detailVC, animated: true)
        }else{
            let alertController = UIAlertController(title: "会员专享",
                                                    message: "\n您还没有登录，是否前往登录？", preferredStyle: .alert)
            let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
            let okAction = UIAlertAction(title: "确认", style: .default, handler: {
                action in
                self.tologin()
                
            })
            alertController.addAction(cancelAction)
            alertController.addAction(okAction)
            self.present(alertController, animated: true, completion: nil)
        }
    }
    
    func tologin(){
        let loginVC = WLoginViewController()
        loginVC.title = "登录"
        let nav = WNavigationController(rootViewController: loginVC)
        present(nav, animated: true, completion: nil)
    }
    
    func toSearch(key: String){
        let detailVC = WSearchProViewController()
        detailVC.title = " "
        detailVC.key = key
        navigationController?.pushViewController(detailVC, animated: true)
    }
}
